﻿//-----------------------------------------------------------------------------
// Copyright (c) BaFang Corporation.  All rights reserved.
//-----------------------------------------------------------------------------

namespace BaFangSpider
{
    using System;
    using LumiSoft.Net.Mail;
using System.Collections.Generic;

    /// <summary>
    /// Summary description for AppleStoreMonitorService
    /// </summary>
    public class AppleStoreMonitorService : MonitorService
    {
        Dictionary<string, ListenerManager> listernerManagers = new Dictionary<string, ListenerManager>(4);
        Dictionary<string, bool> shouldNotifies = new Dictionary<string, bool>(4);
        const string hk_iphone4 = @"http://store.apple.com/hk/browse/home/shop_iphone/family/iphone?";
        const string cn_iphone4 = @"http://store.apple.com/cn/browse/home/shop_iphone/family/iphone?";

        private AppleStoreMonitorService()
        {
            this.mailAddress = MailAccounts.GetInstance().Apple;
            listernerManagers.Add(hk_iphone4,
                new ListenerManager("hk_iphone4_listerns.xml", this.mailAddress));
            listernerManagers.Add(cn_iphone4,
                new ListenerManager("cn_iphone4_listerns.xml", this.mailAddress));

            shouldNotifies.Add(hk_iphone4, true);

            shouldNotifies.Add(cn_iphone4, true);
        }

        private static AppleStoreMonitorService instance = null;

        public static AppleStoreMonitorService GetInstance()
        {
            if (instance == null)
            {
                instance = new AppleStoreMonitorService();
            }
            return instance;
        }

        protected override void  UpdateListenserRegisteredService(string interest, string message)
        {
            // remove originals
            foreach (ListenerManager users in this.listernerManagers.Values)
            {
                users.RemoveListener(interest);
            }
            if (!string.IsNullOrEmpty(message))
            {
                AppleService service = ServiceBase.CreateFromString<AppleService>(message) as AppleService;
                foreach (AppleServiceEntity entity in service.Entities)
                {
                    if (string.Equals(entity.StoreLocation, "中国内地", StringComparison.Ordinal))
                    {
                        this.listernerManagers[cn_iphone4].AddListener(interest, "");
                    }
                    else
                    {
                        this.listernerManagers[hk_iphone4].AddListener(interest, "");
                    }
                }
            }
        }

        protected override void CheckWebSites()
        {
            lock (this.listernerManagers)
            {

                Logger logger = Logger.GetLogger();
                logger.Write(DateTime.Now.ToString() + ": start check apple store html");

                foreach (string address in this.listernerManagers.Keys)
                {
                    CheckAdress(address, ">选择<", "暂无供应");
                }

                logger.Write(DateTime.Now.ToString() + ": End check apple store html");
            }
        }

        private void CheckAdress(string address, string keyWords1, string keyWords2)
        {
            string content = HtmlUtility.GetHtml(address);
            content = content.Substring(10000);
            if (IsOpen(content, keyWords1, keyWords2))
            {
                Logger.GetLogger().Write(DateTime.Now.ToString() + ": Apple store is open !!!");
                if (this.shouldNotifies[address])
                {
                    this.listernerManagers[address].NotifyListens("苹果内地或香港官网开始出售IPhone4了，快去抢购！",
                        @"抢购地址:" + address + ConstStrings.UnregisterAlert);
                    this.shouldNotifies[address] = false; // Only notify once.
                }
            }
            else
            {
                Logger.GetLogger().Write(DateTime.Now.ToString() + ": Apple cn/hk store is not open !!!");
                this.shouldNotifies[address] = true; // Reset.
            }
        }

        // for china: keyWords1 = ">选择<"; keyWorkds2 = "暂无供应"
        private bool IsOpen(string content, string keyWords1, string keyWords2)
        {
            int index = 1;
            int count1 = -1;
            int count2 = -1;
            while (index > 0)
            {
                index += 20;
                index = content.IndexOf(keyWords1, index);
                count1++;
            }
            index = 1;
            while (index > 0)
            {
                index += 20;
                index = content.IndexOf(keyWords2, index);
                count2++;
            }

            return (count1 >= 2) && (count2 <= 1);
        }
    }
}